import json
import socket
import time
from tkinter import Image
from typing import io

import numpy as np
from django.contrib.auth import authenticate, login
from django.core.signals import request_finished
from django.dispatch import receiver
from django.shortcuts import render, redirect
from django.http.response import JsonResponse
from django.http.response import StreamingHttpResponse
# Create your views here.
from django.views.decorators import gzip
from rest_framework import mixins, status
from rest_framework.authentication import BasicAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet

from graduate_back import settings
from main.models import CarsObject, User, VersionControl,Logs
from main.serializer import UserSerializer
import cv2


def GetCarList(request):
    carList =list(CarsObject.objects.all().values())
    return JsonResponse(carList,safe=False)

class UserinfoViewset(GenericViewSet, mixins.RetrieveModelMixin, mixins.ListModelMixin, mixins.CreateModelMixin):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    authentication_classes = [BasicAuthentication]
    permission_classes = [IsAuthenticated, ]

    def retrieve(self, request, *args, **kwargs):
        print(request.user)
        username = request.query_params.get("username")
        password = request.query_params.get("password")
        try:
            instance = authenticate(username=username, password=password)
            if instance is not None:
                print(request.user)
                serializer = self.get_serializer(instance)
                return Response({"code": 200, "data": serializer.data}, status=status.HTTP_200_OK)
            else:
                return Response({"code": 404, "errmsg": "用户名或密码错误"}, status=status.HTTP_404_NOT_FOUND)
        except Exception:
            # return JsonResponse({"code": 404, "errmsg": "用户名或密码错误"})
            return Response({"code": 404, "errmsg": "用户名或密码错误"}, status=status.HTTP_404_NOT_FOUND)


def downloadApp(request):
    new_app = VersionControl.objects.all().last()
    new_app.download_num = new_app.download_num+1
    new_app.save()
    return redirect("/"+settings.MEDIA_URL+str(new_app.app))

def introducePage(request):
    return render(request,'introduce.html')

def statisticsPage(request):
    data = {
        "allLogs":"52136",
        "errLogs":"3213"
    }
    return render(request,'statistics.html',data)

def check_update(request):
    current_version = request.GET.get("version")
    new_app = VersionControl.objects.all().last()
    if new_app:
        if (float(current_version) < new_app.version):
            url = 'downloadapp/'
            return JsonResponse({"code": 200, "msg": str(new_app.version)+"已发布！", "url": url, "new": new_app.version,"detail":new_app.detail})
        else:
            return JsonResponse({"code": 201, "msg": "您使用的就是最新版本！"})
    else:
        return JsonResponse({"code": 201, "msg": "您使用的就是最新版本！"})


def uploadLogs(request):
    if(request.method == "POST"):
        data = json.loads(request.body.decode('utf-8'))
        print(data)
        log = Logs.objects.create(equName=data['equName'],detail=data['detail'],car_id=data['carid'],state=data['state'],user_id=data['userid'])
        log.save()
    return JsonResponse({'code':200,'message':"记录上传成功"})


def video_feed(request):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)
    s.bind(("0.0.0.0", 9090))
    while True:
        data, IP = s.recvfrom(100000)
        bytes_stream = io.BytesIO(data)
        image = Image.open(bytes_stream)
        img = np.asarray(image)
        img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
        yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + image + b'\r\n')

    response = StreamingHttpResponse(generate(), content_type='multipart/x-mixed-replace; boundary=frame')

    return response


def user_login(request):
    request_data = json.loads(request.body.decode('utf-8'))
    user = authenticate(username=request_data['username'],password=request_data['password'])
    if user:
        # 登录
        login(request,user)

        return JsonResponse({'code':200,'message':"登录成功",'userid':user.id})
    else:
        return JsonResponse({'code':404,'message':"用户名或密码错误"},status=404)

